package com.gang.music.system.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.gang.music.system.entity.Song;
import com.gang.music.system.entity.SongInfo;
import com.gang.music.system.mapper.SongInfoMapper;
import com.gang.music.system.mapper.SongMapper;
import com.gang.music.system.mapper.UserSongMapper;
import com.gang.music.system.service.SongService;
import com.smallchill.core.toolbox.Func;
import com.smallchill.core.toolbox.kit.DateTimeKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gang
 * @since 2017-10-26
 */
@Service
public class SongServiceImpl extends ServiceImpl<SongMapper, Song> implements SongService {

	@Autowired
	private SongMapper songMapper;
	
	@Autowired
	private SongInfoMapper songInfoMapper;
	
	@Autowired
	private UserSongMapper userSongMapper;
	
	@Override
	public List<Song> getMySong(Long userId) {
		
		return songMapper.findByUserId(userId);
	}
	
	@Override
	public void increase(Long songId) {
		
		Song song = songMapper.selectWithInfoById(songId);
		SongInfo songInfo = song.getSongInfo();
		songInfo.increasePlayTime();
		songInfoMapper.updateById(songInfo);
	}

	@Override
	public boolean saveOrUpdate(Song song) {
		try{
			//如果是新添加
			if(Func.isEmpty(song.getId())) {
				song.setInputTime(DateTimeKit.date());
				//处理歌曲名
				dealFileName(song);
				SongInfo songInfo = new SongInfo();
				songInfoMapper.insert(songInfo);
				song.setSongInfoId(songInfo.getId());
				
				songMapper.insert(song);
			}else {
				songMapper.updateById(song);
			}
			return true;
		}catch(Exception e){
			return false;
		}
	}

	//截取C:\fakepath\****
	private void dealFileName(Song song) {
		
		if(song.getFileName().lastIndexOf(File.separator) != -1) {
			String fileName = subStr(song.getFileName());
			song.setFileName(fileName);
		}
		if(song.getImageName().lastIndexOf(File.separator) != -1) {
			String imageName = subStr(song.getImageName());
			song.setImageName(imageName);
		}
		if(song.getLyricName().lastIndexOf(File.separator) != -1) {
			String lyricName = subStr(song.getLyricName());
			song.setLyricName(lyricName);
		}
	}
	
	private String subStr(String fileName) {
		
		return fileName.substring(fileName.lastIndexOf(File.separator) +1);
	}

	@Override
	public List<Song> findAllWithInfo() {
		
		return songMapper.selectWithInfo();
	}

	@Override
	public Long queryTotalSongNum() {
		
		return songMapper.queryTotalSongNum();
	}

	
}
